package com.newtouch.cq.base.starter.lang.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import com.newtouch.cq.lang.em.BaseExceptionEnum;
import com.newtouch.cq.lang.exception.IMccExceptionInfo;
import com.newtouch.cq.lang.exception.MccBizException;

import java.util.Collection;
import java.util.Map;


/**
 * 自定义对象工具
 *
 * @author rokeRen
 */
public class OBJutil {


    /**
     * 对象属性判空，并抛出相应的异常
     *
     * @param verified 判空字段为key,异常枚举为value
     * @param c        要判空的对象
     * @param log      判空处对应类的日志类
     * @param way      调用此方法的类.方法名
     * @return
     * @author roke
     */
    public static void verifAttribute(Map<String, IMccExceptionInfo> verified, Object c, Log log, String way) {
        if (ObjectUtil.isNull(c)) {
            log.error("{}：入参对象不能为空，req:{}", way, c);
            throw new MccBizException(BaseExceptionEnum.ERROR);
        }
        Map<String, Object> map = BeanUtil.beanToMap(c);
        for (String key : verified.keySet()) {
            if (ObjectUtil.isNull(map.get(key))) {
                log.error("{}：参数{}不能为空，{}:{}", way, key, key, map.get(key));
                throw new MccBizException(verified.get(key));
            }
            Object v = map.get(key);
            if (v instanceof Collection && CollUtil.isEmpty((Collection) v)) {  //集合判空
                log.error("{}：参数{}不能为空，{}:{}", way, key, key, map.get(key));
                throw new MccBizException(verified.get(key));
            } else if (v instanceof String && StrUtil.isEmpty((String) v)) { //字符串判空
                log.error("{}：参数{}不能为空，{}:{}", way, key, key, map.get(key));
                throw new MccBizException(verified.get(key));
            }
        }
    }

}
